package org.itboys.mobile.service.mongo.weixin;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.itboys.mobile.util.AesCbcUtil;
import org.itboys.mobile.util.HttpHelper;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 作者：zzq
 * 时间：2018/4/14
 * 描述：
 */
@Service
public class SundayWeixinUserInfoService {
    public String getUserInfo(String code,String encryptedData,String iv) throws Exception {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx02e3272ffba9ecf0&secret=842e47f233311d24796621fd1f893d85&js_code=" + code + "&grant_type=authorization_code";
        //通过Gson对象的fromJson方法将返回的json字符串转换为JavaBean
        PostMethod postMethod = new PostMethod(url);
        HttpClient httpclient = HttpHelper.getHttpClient();
        httpclient.executeMethod(postMethod);
        String createResult = postMethod.getResponseBodyAsString();
        //System.out.println("输出结果为"+createResult);
        JSONObject json = (JSONObject) JSONObject.parse(createResult);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
      /*  System.out.println("seesion_key===========" + session_key);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        System.out.println("openid===========" + openid);*/
        String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
        System.out.println(result);
        return result;
    }

    public String getOpenId(String code) throws IOException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx02e3272ffba9ecf0&secret=842e47f233311d24796621fd1f893d85&js_code=" + code + "&grant_type=authorization_code";
        //通过Gson对象的fromJson方法将返回的json字符串转换为JavaBean
        PostMethod postMethod = new PostMethod(url);
        HttpClient httpclient = HttpHelper.getHttpClient();
        httpclient.executeMethod(postMethod);
        String createResult = postMethod.getResponseBodyAsString();
        System.out.println("输出结果为"+createResult);
        JSONObject json = (JSONObject) JSONObject.parse(createResult);
        System.out.println("返回结果为"+json.toString());
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        System.out.println("seesion_key===========" + session_key);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        System.out.println("openid===========" + openid);
        return openid;
    }
}
